package org.devbg.academy.corejava.shop.db.daos;

import java.util.List;

import org.devbg.academy.corejava.shop.db.entities.BasePojo;
import org.devbg.academy.corejava.shop.db.utils.HibernateSessionManager;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

public abstract class BaseDAO<E extends BasePojo> {
	private Session session;
	private Class<E> entityClass;

	public BaseDAO(Class<E> clazz) {
		this.session = HibernateSessionManager.getCurrentSession();
		this.entityClass = clazz;
	}

	protected Criteria createCriteria() {
		return this.session.createCriteria(this.entityClass);
	}

	@SuppressWarnings("unchecked")
	public List<E> findAll() {
		Criteria findAllCriteria = createCriteria();
		List<E> result = findAllCriteria.list();
		return result;
	}

	public Long countAll() {
		Criteria findAllCriteria = createCriteria().setProjection(
				Projections.rowCount());
		Long result = (Long) findAllCriteria.uniqueResult();
		return result;
	}

	@SuppressWarnings("unchecked")
	public E findByPrimaryKey(Long id) {
		Criteria findByPrimaryKeyCriteria = this.createCriteria().add(
				Restrictions.eq("Id", id));
		findByPrimaryKeyCriteria.setMaxResults(1);
		E result = (E) findByPrimaryKeyCriteria.uniqueResult();
		return result;
	}

}
